package com.pomr.controller.sys;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.City;
import com.pomr.model.sys.Coutry;
import com.pomr.model.sys.Province;
import com.pomr.model.sys.User;
import com.pomr.service.common.CommonService;
import com.pomr.service.sys.AgencyService;
import com.pomr.util.common.CallMessage;
import com.pomr.util.common.CommonData;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
import com.pomr.util.page.PageManager;
import com.pomr.util.page.PageParam;
/**
 * 机构
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/agency")
public class AgencyController {
	@Autowired
	@Qualifier("agencyServiceImpl")
	private AgencyService agencyService;
	@Autowired
	@Qualifier("commonServiceImpl")
	private CommonService commonService;
	
	/**
	 * 机构首页
	 * @return
	 */
	@RequestMapping(value="/first",method=RequestMethod.GET)
	public String first(HttpSession session, Model model){
		
		return "sys/agency/first";
	}
	
	/**
	 * 查询机构
	 * @return
	 */
	@RequestMapping(value="/select",method=RequestMethod.GET)
	public String select(Agency agency, String provinceId, String cityId, String coutryId, String page, Model model){
		try{
			Page<Agency> agencys = agencyService.findAgencys(agency, provinceId, cityId, coutryId,page);
			model.addAttribute("agencys", agencys.getRows());
			PageManager pm = null;
			model.addAttribute("page", pm);
//			System.out.println("总页数："+pm.getTotalPage());
//			System.out.println("每页条数："+pm.getPageSize());
//			System.out.println("页码："+pm.getCunrrentPage());
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "sys/agency/show";
	}
	
	/**
	 * 获取所有的省份信息
	 * @return
	 */
	@RequestMapping(value="/allProvince",method=RequestMethod.POST)
	@ResponseBody
	public List<Province> getAllProvince(HttpSession session){
		List<Province> provinces = null;
		User user  = (User) session.getAttribute("user");
		try{
			if(user.getRole().getId() == 2){//超级管理员 获取全部省信息
				provinces = agencyService.getAllProvince();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return provinces;
	}
	
	/**
	 * 获取所有的省份信息-机构信息
	 * @return
	 */
	@RequestMapping(value="/inter-allProvince",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData getAllProvinceInter(HttpServletRequest request){
		List<Province> provinces = null;
		List<City> citys = null;
		List<Coutry> coutrys = null;
		List<Agency> agencys = null;
		ResponseData pd = null;
		try{
			User user  = JWT.findUserByToken(request);
			provinces = (List<Province>) CommonData.data.get("Province");
			citys = (List<City>) CommonData.data.get("City");
			coutrys = (List<Coutry>) CommonData.data.get("Coutry");
			agencys = agencyService.findAgencysOfUser(user);
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		pd = ResponseData.ok();
		pd.putDataValue("provinces", provinces);
		pd.putDataValue("citys", citys);
		pd.putDataValue("coutrys", coutrys);
		pd.putDataValue("agencys", agencys);
		return pd;
	}
	
	/**
	 * 获取所有的市信息
	 * @return
	 */
	@RequestMapping(value="/allCity",method=RequestMethod.POST)
	@ResponseBody
	public List<City> getAllCity(HttpSession session, @RequestBody Map<String, String> map){
		List<City> citys = null;
		User user  = (User) session.getAttribute("user");
		try{
			String provinceId = map.get("provinceId").toString().trim();
			citys = agencyService.getAllCity(provinceId);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return citys;
	}
	
	/**
	 * 获取所有的县信息
	 * @return
	 */
	@RequestMapping(value="/allCoutry",method=RequestMethod.POST)
	@ResponseBody
	public List<Coutry> getAllCoutry(HttpSession session, @RequestBody Map<String, String> map){
		List<Coutry> coutrys = null;
		User user  = (User) session.getAttribute("user");
		try{
			String cityId = map.get("cityId").toString().trim();
			coutrys = agencyService.getAllCoutry(cityId);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return coutrys;
	}
	
	/**
	 * 添加机构
	 * @return
	 */
	@RequestMapping(value="/insert",method=RequestMethod.GET)
	public String insertAgency(HttpSession session, Model model){
		User user  = (User) session.getAttribute("user");
		model.addAttribute("user", user);
		return "sys/agency/insert";
	}
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public String insertAgency(HttpSession session, Model model, Agency agency){
		CallMessage cm = null;
		System.out.println(agency.getCoutry().getId());
		try {
			User user  = (User) session.getAttribute("user");
			agency.setCreateUser(user);
			agency.setCreateName(user.getName());
			agency.setCreateTime(new Date());
			System.out.println(agency.toString());
			if(agencyService.insertAgency(agency)){
				cm = new CallMessage("true", "添加机构成功");
			}else{
				cm = new CallMessage("false", "数据库插入失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			cm = new CallMessage("false", "数据库异常："+e.getMessage());
		}
		session.setAttribute("cm", cm);
		return "sys/agency/insert";
	}
	
	/**
	 * 添加机构--json
	 * @param agency
	 * @return
	 */
	@RequestMapping(value="/inter-insert",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData insertAgencyInter(@RequestBody Agency agency,HttpServletRequest request){
		ResponseData pd = null;
		System.out.println(agency==null?null:agency.getName());
		try{
			User user  = JWT.findUserByToken(request);
			agency.setCreateUser(user);
			agency.setCreateName(user.getName());
			agency.setCreateTime(new Date());
			if(agencyService.insertAgency(agency)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	
	@RequestMapping(value="/inter-validate",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData validateAgency(@RequestBody Map<String,String> map,HttpServletRequest request){
		ResponseData pd = null;
		try{
			String identifier = map.get("identifier");
			if(identifier == null){
				pd = ResponseData.custom("机构编号获取失败");
				return pd;
			}
			if(agencyService.valiAgency(identifier)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-select",method=RequestMethod.POST)
	@ResponseBody
	public Page<List<Agency>> selectAgencyInter(HttpServletRequest request,@RequestBody Map<String, Object> map){
		System.out.println("--------------");
		Agency agency = new Agency();
		Page<List<Agency>> p = null;
		try {
			p = agencyService.findAgencys(agency, null, null, null, map.get("page").toString(), map.get("limit").toString());
			return p;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value="/inter-selectcont",method=RequestMethod.POST)
	@ResponseBody
	public Page<List<Agency>> selectAgencyInterCont(HttpServletRequest request,@RequestBody Map<String, Object> map){
		Agency agency = new Agency();
		Page<List<Agency>> p = null;
		try {
			agency.setName(map.get("agname").toString());
			agency.setIdentifier(map.get("agidentifier").toString());
			agency.setStatus(map.get("agstatus").toString());
			agency.setPatientId((map.get("agpatientid")==null || map.get("agpatientid").toString().equals(""))?null:Integer.valueOf(map.get("agpatientid").toString()));
			p = agencyService.findAgencys(agency, map.get("agsheng")==null?null:map.get("agsheng").toString(), 
					map.get("agshi")==null?null:map.get("agshi").toString(), 
					map.get("agxian")==null?null:map.get("agxian").toString(), 
					map.get("page").toString(), map.get("limit").toString());
			return p;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取基本信息 更新前
	 * @return
	 */
	@RequestMapping(value="/inter-selectinfo",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData selectInfoBeforeUp(HttpServletRequest request,@RequestBody Map<String, Object> map) {
		ResponseData pd = null;
		List<Province> provinces = null;
		List<City> citys = null;
		List<Coutry> coutrys = null;
		List<Agency> agencys = null;
		Agency ag = null;
		try{
			String id = map.get("id").toString();
			if(id == null || id.trim().equals("")){
				pd = ResponseData.custom("机构信息获取失败");
				return pd;
			}
			//机构信息
			//用户下机构列表
			//省市县信息
			User user  = JWT.findUserByToken(request);
			provinces = (List<Province>) CommonData.data.get("Province");
			citys = (List<City>) CommonData.data.get("City");
			coutrys = (List<Coutry>) CommonData.data.get("Coutry");
			agencys = agencyService.findAgencysOfUser(user);
			ag = agencyService.findAgencyAllInfo(Integer.valueOf(id));
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		pd = ResponseData.ok();
		Map<String, Object> info = new HashMap<String, Object>();
		info.put("provinces", provinces);
		info.put("citys", citys);
		info.put("coutrys", coutrys);
		info.put("agencys", agencys);
		info.put("ag", ag);
		pd.putDataValue("info", info);
		return pd;
	}
	
	@RequestMapping(value="/inter-saveagency",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData saveAgencyOfUpdate(HttpServletRequest request,@RequestBody Agency agency) {
		ResponseData pd = null;
		try{
			if(agencyService.updateAgency(agency)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-deleteagency",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData dateleAgencyInter(HttpServletRequest request,@RequestBody Map<String, Object> map) {
		ResponseData pd = null;
		try{
			String[] ids = map.get("id").toString().split(",");
			List<String> idl = Arrays.asList(ids);
			if(agencyService.deleteAgencys(idl)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-editbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editAgencyInterBefore(HttpServletRequest request,@RequestBody Map<String, Object> map) {
		ResponseData pd = null;
		try{
			List<String> ids = JSONArray.parseArray(map.get("id").toString(), String.class);
			if(agencyService.deleteAgencys(ids)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	/**
	 * 获取基本信息 更新前
	 * @return
	 */
	@RequestMapping(value="/inter-selectbefinfo",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData selectInfoBeforeSel(HttpServletRequest request) {
		ResponseData pd = null;
		List<Province> provinces = null;
		List<City> citys = null;
		List<Coutry> coutrys = null;
		List<Agency> agencys = null;
		try{
			//机构信息
			//用户下机构列表
			//省市县信息
			User user  = JWT.findUserByToken(request);
			provinces = (List<Province>) CommonData.data.get("Province");
			citys = (List<City>) CommonData.data.get("City");
			coutrys = (List<Coutry>) CommonData.data.get("Coutry");
			agencys = agencyService.findAgencysOfUser(user);
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		pd = ResponseData.ok();
		Map<String, Object> info = new HashMap<String, Object>();
		info.put("provinces", provinces);
		info.put("citys", citys);
		info.put("coutrys", coutrys);
		info.put("agencys", agencys);
		pd.putDataValue("info", info);
		return pd;
	}
	
	/**
	 * 获取用户所属以及下属机构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchtouser",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchAgencysOfUser(HttpServletRequest request) {
		ResponseData pd = null;
		try {
			User user  = JWT.findUserByToken(request);
			List<Agency> agencys = agencyService.searchAgencysOfUser(user);
			if(agencys == null || agencys.isEmpty()){
				pd = ResponseData.notFound();
			}else{
				pd = ResponseData.ok();
				pd.putDataValue("agencys", agencys);
			}
			//获取权限信息
			List roles = commonService.findRolesByUser(user);
			if(roles == null || roles.isEmpty()){
				pd = ResponseData.notFound();
			}else{
				pd.putDataValue("roles", roles);
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 通过条件查询机构信息 （机构编号、最顶级机构、状态）
	 * @return
	 */
	@RequestMapping(value="/inter-searchAgencysCond",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<Agency>> searchAgencysByCond(PageParam param) throws Exception{
		String page = param.getPage();
		String limit = param.getLimit();
		Map<String, String> map = param.getParams();
		String identifier = map.get("identifier");
		String patientid = map.get("patientId");
		String status = map.get("status");
		return agencyService.searchAgencysByCond(identifier, patientid, status, limit, page);
	}
	
	/**
	 * 更改机构状态
	 * @param request
	 * @param agency
	 * @return
	 */
	@RequestMapping(value="/inter-status",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData changeStatus(HttpServletRequest request,@RequestBody Agency agency) {
		ResponseData pd = null;
		try {
			if(agencyService.changeStatus(agency)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}

	/**
	 * 获取所有机构列表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/app-searchagencys",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData searchAgencys() throws Exception{
		ResponseData pd = null;
		List<Agency> agencies = agencyService.searchAllAgencys();
		if(agencies!=null && agencies.size()>0){
			pd = ResponseData.ok();
			pd.putDataValue("agencys",agencies);
		}else{
			pd = ResponseData.custom("没有可用机构");
		}
		return pd;
	}

}
